package com.lune.job.framework.role;

import com.lune.job.framework.exception.AuthException;
import com.lune.job.framework.redis.RedisUtil;
import com.lune.job.utils.UserThreadLocal;
import com.lune.job.vo.UserData;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 *
 **/
@Component
@Aspect
public class RoleAspect {
    @Autowired
    private RedisUtil redisUtil;
    @Pointcut
    public void pointCut(){

    }
    @Before("execution(* com.lune.job.controller.*Controller.*(..))")
    public void before(JoinPoint joinPoint){
        System.out.println("执行前==================");
        MethodSignature signature= (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        System.out.println(method.getName());
        // 通过方法获取注解
        RequireRoles annotation = method.getAnnotation(RequireRoles.class);
        if (annotation!=null){
            String token = UserThreadLocal.get();//本地线程获取token
            UserData userData = (UserData) redisUtil.get(token);
            if (userData!=null){
                if (!String.valueOf(userData.getType()).equals(String.valueOf(annotation.type().getCode()))){
                    //type值不匹配
                    throw new AuthException("没有权限");
                }
            }else{
                throw new AuthException("没有权限");

            }
            System.out.println(annotation);
            System.out.println(annotation.type());
        }
    }
}
